const express = require('express');
const router = express.Router();
const db = require('../db');

// 获取所有traffic_event数据
router.get('/', async (req, res) => {
  try {
    const sql = `SELECT * FROM traffic_event`;
    const data = await db.getAll(sql);
    res.json({
      code: 200,
      data,
    });
  } catch (error) {
    // console.log(error);
    res.json({
      code: 500,
      message: '服务器错误',
    });
  }
});

// 获取单个traffic_event数据
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const sql = `SELECT * FROM traffic_event WHERE id=${id}`;
    const data = await db.getOne(sql);
    res.json({
      code: 200,
      data,
    });
  } catch (error) {
    // console.log(error);
    res.json({
      code: 500,
      message: '服务器错误',
    });
  }
});

// 新增traffic_event数据
router.post('/', async (req, res) => {
  try {
    const {
      user_id,
      event_type,
      event_describe,
      road_section_id,
      event_driver,
      event_car_number,
    } = req.body;
    const sql = `INSERT INTO traffic_event (user_id, event_type, event_describe, road_section_id, event_driver, event_car_number) VALUES (${user_id}, '${event_type}', '${event_describe}', '${road_section_id}', '${event_driver}', '${event_car_number}')`;
    const data = await db.exec(sql);
    res.json({
      code: 200,
      message: '新增成功',
    });
  } catch (error) {
    // console.log(error);
    res.json({
      code: 500,
      message: '服务器错误',
    });
  }
});

// 修改traffic_event数据
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const {
      user_id,
      event_type,
      event_describe,
      road_section_id,
      event_driver,
      event_car_number,
    } = req.body;
    const sql = `UPDATE traffic_event SET user_id=${user_id}, event_type='${event_type}', event_describe='${event_describe}', road_section_id='${road_section_id}', event_driver='${event_driver}', event_car_number='${event_car_number}' WHERE id=${id}`;
    const data = await db.exec(sql);
    res.json({
      code: 200,
      message: '修改成功',
    });
  } catch (error) {
    // console.log(error);
    res.json({
      code: 500,
      message: '服务器错误',
    });
  }
});

// 删除traffic_event数据
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const sql = `DELETE FROM traffic_event WHERE id=${id}`;
    const data = await db.exec(sql);
    res.json({
      code: 200,
      message: '删除成功',
    });
  } catch (error) {
    // console.log(error);
    res.json({
      code: 500,
      message: '服务器错误',
    });
  }
});

module.exports = router;
